<?php

namespace App\Console\Commands;

use App\Enum\MonitorEnum;
use App\Enum\ThirdOrderEnum;
use App\Events\OrderCreated;
use App\Models\OrderModel;
use App\Models\ThirdOrderAllModel;
use App\Services\MonitorService;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class ImmigrateOrdersCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order:immigrate-third';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '将三方订单导入订单总表。';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        while(1) {
            $second = date('s');

            if ($second >= 55) {
                $this->info("saveOrderAddressCommand second = $second, wait for next time.");
                break;
            } else  $this->info("saveOrderAddressCommand second = $second, keep going.");

            $row = ThirdOrderAllModel::query()->where(['transfer_status' => ThirdOrderEnum::THIRD_ORDER_TRANSFER_NO])->orderBy('id')->first();

            if( empty($row) ) {
                sleep(1);
                continue;
            }

            // 获取订单所需要的数据
            $rowData = $this->_formatOrderData($row->toArray());

            try {
                // 执行导入
                $this->_importOrder($rowData);

                // 标记导入成功
                $row->update(['transfer_status'=>ThirdOrderEnum::THIRD_ORDER_TRANSFER_YES,'memo'=>'成功']);
            }catch (Exception $e){
                $this->_exceptionMonitor(sprintf('将三方订单导入总表失败：订单号(%s)，E=%s.', $rowData['order_no'],$e->getMessage()));
                //  标记导入 失败
                $row->update(['transfer_status'=>ThirdOrderEnum::THIRD_ORDER_TRANSFER_ERROR,'memo'=>$e->getMessage()]);
                Log::error(sprintf('将三方订单导入总表失败：订单号(%s).', $rowData['order_no']));
            }
            sleep(1);
        }
        return 0;
    }
    private function _exceptionMonitor( string $memo )
    {
        MonitorService::addException(MonitorEnum::MONITOR_TYPE_THIRD_TO_ORDERS, $memo);
    }

    /**
     * 返回订单所需要的数据
     *
     * @param $row
     * @return array
     */
    private function _formatOrderData($row): array
    {
        $rowData = [];
        $fields = [
            'city_code', 'user_phone', 'user_id', 'order_no'
            , 'start_address', 'start_adcode',  'start_address_detail', 'start_location'
            , 'end_address', 'end_adcode','end_address_detail', 'end_location'
            ,'vehicle_type', 'vehicle_use_type', 'start_time', 'distance', 'duration'
            ,'platform_id', 'third_order_no','amount_type', 'amount', 'payment_method'
            ,'flight_no'
        ];
        foreach( $fields as $field ) {
            $rowData[$field] = $row[$field];
        }
        return $rowData;
    }

    /**
     * 导入单条数据
     *
     * @param array $data
     * @return void
     * @throws Exception
     */
    private function _importOrder( array $data ): void
    {
        try {
            $orderInfo =  OrderModel::create($data);
           // 异步执行 订单成功后的操作
            event(new OrderCreated($orderInfo));
        }catch (Exception $e){
            throw new Exception(sprintf("导入三方订单(%s)异常：%s", $data['third_order_no'], $e->getMessage()));
        }
    }
}
